package com.ccc.poi.tl.service.impl;

import cn.hutool.core.date.DateUtil;
import com.ccc.poi.tl.entity.TableData;
import com.ccc.poi.tl.service.TestTableService;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author superC
 * @version 1.0.0
 * @date 2023-07-28
 */

@Service
public class TestTableServiceImpl implements TestTableService {

    public static final String ASSET_CHANGE_FILE_PATH = "/doc/word_table.docx";

    @Override
    public XWPFTemplate exportDoc() throws IOException {
        //1 获取模板文件流
        File resourceFile = new ClassPathResource(ASSET_CHANGE_FILE_PATH).getFile();

        //2 构建word数据
        Map<String, Object> content = new HashMap<>();
//        content.put("assets", fillAssets());
        content.put("assets", getTableDatas());

        //3 创建行循环策略
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy(true);
        // 告诉模板引擎，要在tagName做行循环,绑定行循环策略
        Configure config = Configure.builder().bind("assets", policy).build();

        // 编译渲染
        return XWPFTemplate.compile(resourceFile, config).render(content);
    }

    /**
     * 转换填充表格数据
     *
     * @return
     */
    private List<Map<String, Object>> fillAssets() {
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            Map<String, Object> table = new HashMap<>();
            table.put("index", i + 1);
            table.put("code", "TMP" + i);
            table.put("name", "测试数据" + i);
            table.put("remark", "备注" + i);
            list.add(table);
        }
        return list;
    }

    /**
     * 转换填充表格数据
     *
     * @return
     */
    private List<TableData> getTableDatas() {
        List<TableData> list = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            TableData table = new TableData();
            table.setIndex(i + 1);
            table.setCode("TMP" + i);
            table.setName("测试数据" + i);
            table.setRemark("备注" + i);
            list.add(table);
        }
        return list;
    }
}
